﻿import sys,urllib
place_name = set()
for line in open("./data/lianjia-bj-ershoufan.csv","r"):
    place_name.add(line.split(",")[0])

import json
def get_coordinate(address):
    params = urllib.urlencode({"ak": "kOoEckO30chV8GtGhqMGFbH8", 'address': address, "city": "北京","output":"json"}) 
    conn = urllib.urlopen("http://api.map.baidu.com/geocoder/v2/?%s" % params)
    data = conn.read()
    conn.close()
    print address+"->"+data
    jdata = json.JSONDecoder().decode(data)
    if jdata["status"] == 0:
        jcoord = jdata["result"]["location"]
        return [jcoord["lng"], jcoord["lat"]]
    else:
        return [0,0]

fsave = file("./data/lianjia-bj-name-coordinate.csv","w")
count = 1
for place in place_name:
    coord = get_coordinate(place)
    print "["+str(count)+"/"+str(len(place_name))+"]"
    count+=1;
    fsave.write(place+","+str(coord[0])+","+str(coord[1])+"\n")
fsave.close()

print "done"
